package com.nep.NEPM.controller;

import com.nep.entity.administrator.User;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.stage.Stage;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SupervisorAllopatricViewController {
    @FXML
    private Button btn_OUT;
    @FXML
    private Button btn_Back;
    @FXML
    private Label lblId;          // 编号
    @FXML
    private Label lblName;        // 姓名
    @FXML
    private Label lblProvince;    // 省份
    @FXML
    private Label lblCity;        // 城市
    @FXML
    private Label lblGrade;       // 污染等级
    @FXML
    private Label lblDate;        // 日期
    @FXML
    private Label lblTime;        // 时间
    @FXML
    private Label lblPhone;
    @FXML
    private Label lblAddress;
    @FXML
    private Label lblDescription;
    @FXML
    private Label lblSex;
    @FXML
    private Label lblBornDate;
    @FXML
    private Label lblDegree;
    @FXML
    private ComboBox<String> cmbProvince;
    @FXML
    private ComboBox<String> cmbCity;
    @FXML
    private ComboBox<String> cmbAllopatricWorker;
    @FXML
    private Button btnAllopatricAssign;
    private SupervisorListViewController parentController;
    private static final String ASSIGNMENT_DIR = "assignments/";
    private static final String ALLOPATRIC_ASSIGNMENT_FILE = "allopatric_assignments.txt";

    private Map<String, List<String>> provinceMap = new HashMap<>();
    // 初始化视图数据的方法
    public void initData(User user, SupervisorListViewController parentController) {
        this.parentController = parentController;
        lblPhone.setText(user.getPhone());
        lblAddress.setText(user.getAddress());
        lblDescription.setText(user.getDescription());
        lblSex.setText(user.getSex());
        lblBornDate.setText(user.getBornDate());
        lblDegree.setText(user.getDegree());
        lblId.setText(user.getId());
        lblName.setText(user.getName());
        lblProvince.setText(user.getProvince());
        lblCity.setText(user.getCity());
        lblGrade.setText(user.getGrade());
        lblDate.setText(user.getDate());
        lblTime.setText(user.getTime());

        provinceMap.put("安徽省", List.of("合肥", "芜湖", "淮南", "阜阳"));
        provinceMap.put("北京市", List.of("北京"));
        provinceMap.put("重庆市", List.of("重庆"));
        provinceMap.put("福建省", List.of("福州", "厦门", "莆田", "泉州"));
        provinceMap.put("甘肃省", List.of("兰州")); // 注：西宁属青海省，此处按用户原分类调整
        provinceMap.put("广东省", List.of("广州", "深圳", "东莞", "佛山", "惠州", "汕头", "珠海", "江门", "湛江"));
        provinceMap.put("广西壮族自治区", List.of("南宁", "柳州", "桂林"));
        provinceMap.put("贵州省", List.of("贵阳"));
        provinceMap.put("海南省", List.of("海口"));
        provinceMap.put("河北省", List.of("石家庄", "唐山", "廊坊", "大同", "秦皇岛", "张家口", "邢台", "保定"));
        provinceMap.put("河南省", List.of("郑州", "洛阳", "开封", "新乡", "南阳"));
        provinceMap.put("黑龙江省", List.of("哈尔滨", "齐齐哈尔", "大庆"));
        provinceMap.put("湖北省", List.of("武汉", "襄阳", "宜昌"));
        provinceMap.put("湖南省", List.of("长沙", "岳阳", "衡阳", "株洲"));
        provinceMap.put("吉林省", List.of("长春", "吉林", "大庆"));
        provinceMap.put("江苏省", List.of("南京", "苏州", "无锡", "南通", "徐州", "盐城", "扬州", "常州"));
        provinceMap.put("江西省", List.of("南昌", "赣州", "上饶"));
        provinceMap.put("辽宁省", List.of("沈阳", "大连", "鞍山", "抚顺", "锦州", "营口"));
        provinceMap.put("内蒙古自治区", List.of("呼和浩特", "包头", "赤峰"));
        provinceMap.put("宁夏回族自治区", List.of("银川"));
        provinceMap.put("山东省", List.of("济南", "青岛", "淄博", "烟台", "临沂", "济宁", "泰安", "潍坊"));
        provinceMap.put("山西省", List.of("太原", "大同", "长治"));
        provinceMap.put("陕西省", List.of("西安", "咸阳"));
        provinceMap.put("上海市", List.of("上海"));
        provinceMap.put("四川省", List.of("成都", "绵阳", "泸州", "宜宾", "南充"));
        provinceMap.put("天津市", List.of("天津"));
        provinceMap.put("新疆维吾尔自治区", List.of("乌鲁木齐"));
        provinceMap.put("西藏自治区", List.of("拉萨"));
        provinceMap.put("云南省", List.of("昆明"));
        provinceMap.put("浙江省", List.of("杭州", "宁波", "温州", "绍兴", "台州", "义乌", "慈溪"));
        provinceMap.put("青海省", List.of("西宁"));
        cmbProvince.setItems(FXCollections.observableArrayList(provinceMap.keySet()));
        cmbProvince.getSelectionModel().clearSelection();
        cmbProvince.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<String>() {
            @Override
            public void changed(ObservableValue<? extends String> observableValue, String oldValue, String newValue) {
                List<String> citys = provinceMap.getOrDefault(newValue, List.of());
                cmbCity.setItems(FXCollections.observableArrayList(citys));
                cmbCity.getSelectionModel().clearSelection();
            }
        });

        // 初始化网格员数据
        ObservableList<String> workers = FXCollections.observableArrayList(
                "异地网格员1", "异地网格员2", "异地网格员3"
        );
        cmbAllopatricWorker.setItems(workers);
    }

    @FXML
    private void AllopatricAssign(ActionEvent event) {
        String targetProvince = cmbProvince.getValue();
        String targetCity = cmbCity.getValue();
        String worker = cmbAllopatricWorker.getValue();

        if (targetProvince == null || targetCity == null || worker == null) {
            showAlert("警告", "请完成所有选项");
            return;
        }

        // 创建任务信息字符串
        String assignmentInfo = String.format(
                "异地指派任务\n" +
                        "编号: %s\n姓名: %s\n原省份: %s\n原城市: %s\n" +
                        "目标省份: %s\n目标城市: %s\n" +
                        "污染等级: %s\n日期: %s\n时间: %s\n" +
                        "联系电话: %s\n地址: %s\n描述: %s\n" +
                        "性别: %s\n出生日期: %s\n学历: %s\n" +
                        "指派给: %s\n指派时间: %s\n\n",
                lblId.getText(), lblName.getText(), lblProvince.getText(), lblCity.getText(),
                targetProvince, targetCity,
                lblGrade.getText(), lblDate.getText(), lblTime.getText(),
                lblPhone.getText(), lblAddress.getText(), lblDescription.getText(),
                lblSex.getText(), lblBornDate.getText(), lblDegree.getText(),
                worker, LocalDate.now()
        );

        // 保存到文件
        saveAssignmentToFile(ALLOPATRIC_ASSIGNMENT_FILE, assignmentInfo);

        if (parentController != null) {
            parentController.updateUserAssignmentStatus(lblId.getText(), true);
        }

        showAlert("成功", "异地指派任务已保存");
        // 关闭当前窗口
        ((Stage) btnAllopatricAssign.getScene().getWindow()).close();
    }

    // 新增方法：保存指派信息到文件
    private void saveAssignmentToFile(String filename, String content) {
        try {
            // 确保目录存在
            new File(ASSIGNMENT_DIR).mkdirs();

            // 追加写入文件
            Files.write(
                    Paths.get(ASSIGNMENT_DIR + filename),
                    content.getBytes(StandardCharsets.UTF_8),
                    StandardOpenOption.CREATE, StandardOpenOption.APPEND
            );
        } catch (IOException e) {
            e.printStackTrace();
            showAlert("错误", "保存指派信息失败: " + e.getMessage());
        }
    }

    // 新增方法：显示提示框
    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
    public void OUT(ActionEvent actionEvent) throws IOException {
        Stage stage = (Stage) btn_OUT.getScene().getWindow();
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../view/IndexView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_OUT.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }
    public void Back(ActionEvent actionEvent) throws IOException {
        Stage stage = (Stage) btn_Back.getScene().getWindow();
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../view/SupervisorLocalView.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();
        Scene scene = btn_Back.getScene();
        scene.setRoot(root);
        stage.setScene(scene);
        stage.show();
    }
}
